<?php

/**
 * Created by PhpStorm.
 * User: 72925
 * Date: 2018/11/23
 * Time: 9:26
 * order: 注册相关操作
 */

namespace app\index\controller;

use think\Controller;
use think\Validate;
use think\Cache;
use app\index\model\User;
use lib\Invite;
use lib\Safety;


class Register extends Controller {
       
    public function register()
    {
		$appid = "wxd175ae1e69006837";
		$secret = "26c09900c47fa037457f5aad8c023a4a";
        $mobile = trim(input('mobile'));
        $verify = trim(intval(input('verify')));
        $password = trim(input('password'));
        $repassword = trim(input('repassword'));
	    $invite   = input('invire');   //上级邀请码
        $js_code = input('code');
        if($js_code)
        {
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $js_code . "&grant_type=authorization_code";

            $api = file_get_contents($url);
            $wxapi = json_decode($api, JSON_FORCE_OBJECT);
            $openid = $wxapi['openid'];
            $safety = new Safety;
            $session3rd =  $safety->safety();  
            $session_key = $wxapi['session_key'];
            $data = array('session3rd'=>$session3rd,'val'=>$session_key.$openid);
            Cache($session3rd,$data);                     
            if($data) 
            {                   
                $rule = [
                    // 'mobile' => 'require|/^1[34578]\d{9}$/',
                    // 'verify' => 'number|max:6',
                    'password' => 'require|/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/',
                    // 'repassword'=> 'alphaNum|length:6,18',
                    // 'invite' =>'require|max:8',
                ];
                $msg = [
                    // 'mobile' => [''=>'','msg'=>'手机号码无效'],
                    // 'verify' => '验证码为随机6位数字',
                    'password' => '密码为6到18位大小写字母和数字组合',
                    // 'repassword' => '密码为6到18位大小写字母和数字组合',
                    // 'invite' =>'邀请码必填',
                ];
        
                $datas = [
                    // 'mobile' => $mobile,
                    // 'verify' => $verify,
                    'password' => $password,
                    // 'repassword'=> $repassword,
                    // 'invite' => $invite,
                ];

                $validate = new Validate($rule,$msg);
                $result = $validate->check($datas);
                $is_code = Cache::get('param');//获取缓存中的验证码
                $user = User::get(['invite'=>$invite]); //验证填写的邀请码
                $ivt = $user['id']; //上级ID
                $grade = $user['grade'];
                $time = date('Y-m-d:H:i:s');//当前时间
                $sevenday = date('Y-m-d:H:i:s',strtotime("+7 day"));
                $testmobile = user::get(['mobile'=>$mobile]);//检测手机号是否注册
                //生成邀请码//判断邀请码是否唯一
                $inv= New Invite;
                $newinvite = $inv->createinvite();                
                $uniqid = User::get(['invite'=>$newinvite]);
                $rid = mt_rand(11111,55555). mt_rand(66666,99999);
                if( $testmobile == NULL && $user !== NULL && $result == true && $password == $repassword && $is_code == $verify && $uniqid == NULL)
              	{	
              		$user = new User;
                    $user->data([ 'mobile' => $mobile, 'password' => MD5($password), 'ivt'=> $ivt, 'invite' => $newinvite, 'openid' => $openid, 'created_at' => $time, 'updated_at' => $sevenday, 'rnumber' => $rid]);
                    $newinsert = $user->save();   
                    $ID = $user->id;                 
                    if($newinsert == 1){                       
                            $arr = array('userId' =>  $ID, 'mobile' => $mobile, 'grade'=> "0", 'session3rd' => $session3rd);
                            $dat = ['code' => 200, 'msg' => '注册成功',$arr];
                            return json_encode($dat, TRUE);
                        }else{
                            $dat = ['code' => 200, 'msg' => '您已经注册成功,请直接登录'];
                            return json_encode($dat, TRUE);
                        }                               
              	} elseif ( $result == false) {                   
                    $dat = ['code' => 400, 'msg' => '密码和重复密码不一致'];
                    return json_encode($dat);
                }  elseif ($is_code != $verify) {
                    $dat = ['code' => 401, 'msg' => '验证码错误'];
                    return json_encode($dat);
                } elseif($user == NULL){
                    $dat = ['code' => 402, 'msg' => '邀请码不存在'];
                    return json_encode($dat);
                }elseif( $testmobile !== NULL){
                    $dat = ['code' => 403, 'msg' => '此手机号码已经注册，请直接登录'];
                    return json_encode($dat);
                }              
            }
        }else{
            echo "请传入code";
        }
    }


    //获取16B随机数
   public function safety()
   { 
        $random_string = '';
        try{
             $fp = @fopen('/dev/urandom','rb');
             if ($fp !== false) {
                    $random_string .= @fread($fp, 16);
                    $pr_bits_arr = unpack('H*', $random_string);
                    $random_string = $pr_bits_arr[1];
                    @fclose($fp);
                }
        } catch( \Exception $e){

            error_log($e->getMessage());

        }   
        return $random_string;
    
    }

}